package org.huntaway.kindergarten.service.common;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;
import org.huntaway.hibernate.SessionManager;
import org.huntaway.kindergarten.po.SysUser;
import org.huntaway.kindergarten.util.Singleton;
import org.huntaway.struts1.preprocessor.Preprocessor;

public class LoginService extends Preprocessor {
	protected SessionManager dateManage = Singleton.dateManage;

	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession session = request.getSession(true);
		if (session.getAttribute("user") != null) {
			return mapping.findForward(SUCC);
		}		
		if (request.getParameter("username") == null
				|| request.getParameter("username").equals("")) {
			return mapping.findForward(INPUT);
		} else {
			return check(mapping, form, request, response);
		}

	}

	public ActionForward check(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		serBean = super.list(mapping, form, request, response);
		HttpSession session = request.getSession(true);
		String userName = request.getParameter("username");
		String passWord = request.getParameter("password");
		Criteria criteria = dateManage.createCriteria(SysUser.class);
		criteria.add(Expression.eq("TCode", userName));
		criteria.add(Expression.eq("Password", passWord));
		@SuppressWarnings("unchecked")
		List<SysUser> resCri = criteria.list();
		SysUser tbUser = null;
		if (resCri.size() == 1) {
			tbUser = resCri.get(0);			
			if (session.getAttribute("user") == null) {
				session.setAttribute("user", tbUser);
			}
		} else {
			request.setAttribute("Name", userName);
			request.setAttribute("Pwd", passWord);
			request.setAttribute("err_mes", "用户名/密码存在问题,请重新输入");
			serBean = mapping.findForward(INPUT);
		}
		return serBean;
	}
}
